<script setup lang="ts">
import * as pdfjsLib from 'pdfjs-dist';
import { ref, watchEffect, onMounted, onUnmounted} from "vue"
import { obsDownload } from "#/utils/obs"
import type { obsDataType } from "#/utils/obs"
import { type PropType } from 'vue';

defineOptions({ name: 'PDF' })
const loading = ref(false)
const props = defineProps({
  obs: {
    type: Object as PropType<obsDataType>,
    default: { Key: '' }
  }
})

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
  '#/utils/pdf.worker.min.js',
  import.meta.url,
).href;

const pdfContainer = ref<any>();
let pdf: any;
let currentArrayBuffer: any;

const download = () => {
  if (!props.obs?.Key) return
  loading.value = true
  obsDownload({ ...props.obs }, (err: any, result: any) => {
    if (err) {
      console.error('获取失败:', err);
      loading.value = false;
      return;
    }
    let { Content } = result.InterfaceResult
    currentArrayBuffer = Content;
    loadPdf(Content);
  })
}

const loadPdf = async (arraybuffer?: any) => {
  if (!pdfContainer.value) return;
  try {
    if (!pdf) {
      pdf = await pdfjsLib.getDocument(arraybuffer).promise;
    }
    const renderPage = async (pageNumber: number) => {
      const page = await pdf.getPage(pageNumber);
      const canvas = document.createElement('canvas');
      
      // 获取父容器尺寸
      const containerRect = pdfContainer.value.getBoundingClientRect();
      const containerWidth = containerRect.width || pdfContainer.value.offsetWidth;
      const containerHeight = containerRect.height || pdfContainer.value.offsetHeight;
      
      // 获取PDF原始尺寸
      const originalViewport = page.getViewport({ scale: 1.0 });
      
      // 计算适合容器的缩放比例
      const scaleX = containerWidth / originalViewport.width;
      const scaleY = containerHeight / originalViewport.height;
      const scale = Math.min(scaleX, scaleY, 2.0); // 限制最大缩放为2倍
      
      // 使用计算出的缩放比例
      const viewport = page.getViewport({ scale });
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      
      // 设置canvas样式确保完全展示
      canvas.style.maxWidth = '100%';
      canvas.style.maxHeight = '100%';
      canvas.style.objectFit = 'contain';
      
      const renderContext: any = {
        canvasContext: canvas.getContext('2d'),
        viewport,
      };
      await page.render(renderContext).promise;
      pdfContainer.value.innerHTML = '';
      pdfContainer.value.append(canvas);
    };
    await renderPage(1);
  } catch (error) {
    console.error('加载时出错:', error);
  }
  loading.value = false
};

// 重新渲染PDF以适应新的容器尺寸
const reRenderPdf = async () => {
  if (pdf && currentArrayBuffer && pdfContainer.value) {
    // await loadPdf(currentArrayBuffer);
  }
};

// 窗口尺寸变化时重新渲染
const handleResize = () => {
  reRenderPdf();
};

onMounted(() => {
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});

watchEffect(() => {
  if (props.obs?.Key) {
    download()
  }
})

</script>
<template>
  <div class="w-full h-full" style="height: 100%; min-height: 400px;">
    <div ref="pdfContainer" class="flex justify-center items-center w-full h-full overflow-hidden" v-loading="loading" v-show="pdf || loading"></div>
    <div class="flex justify-center items-center w-full h-full" v-if="!pdf && !loading" style="height: 100%; min-height: inherit;">
      <el-empty description="暂无数据" />
    </div>
  </div>
</template>
